<template>
  <div>
    <el-form
      :model="inputForm"
      size="small"
      ref="inputForm"
      v-loading="loading"
      :class="method === 'view' ? 'readonly' : ''"
      :disabled="method === 'view'"
      label-width="120px"
    >
      <el-row :gutter="15">
        <div class="line-bottom">套餐配置</div>
        <el-col :span="24">
          <el-form-item
            label="套餐名称:"
            prop="mealName"
            :rules="[
              {
                required: true,
                message: '套餐名称不能为空',
                trigger: 'blur',
              },
            ]"
          >
            <el-input
              v-model="inputForm.mealName"
              placeholder="请填写套餐名称"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="套餐类型:"
            prop="mealType"
            :rules="[
              {
                required: true,
                message: '套餐类型不能为空',
                trigger: 'blur',
              },
            ]"
          >
            <el-select
              class="width-100"
              size="small"
              v-model="inputForm.mealType"
              placeholder="请选择套餐类型"
            >
              <el-option
                v-for="item in mealTypeList"
                :key="item.dictKey"
                :label="item.dictValue"
                :value="item.dictKey"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="活动类型:"
            prop="mealActiveType"
            :rules="[
              {
                required: true,
                message: '活动类型不能为空',
                trigger: 'blur',
              },
            ]"
          >
            <el-select
              class="width-100"
              size="small"
              v-model="inputForm.mealActiveType"
              placeholder="请选择活动类型"
            >
              <el-option
                v-for="item in mealActiveTypeList"
                :key="item.dictKey"
                :label="item.dictValue"
                :value="item.dictKey"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="套餐状态:"
            prop="isEnable"
            :rules="[
              {
                required: true,
                message: '套餐状态不能为空',
                trigger: 'blur',
              },
            ]"
          >
            <el-select
              class="width-100"
              size="small"
              v-model="inputForm.isEnable"
              placeholder="请选择套餐状态"
            >
              <el-option
                v-for="item in isEnableList"
                :key="item.dictKey"
                :label="item.dictValue"
                :value="item.dictKey"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="服务费（元）:"
            prop="setServiceCharge"
            :rules="[
              {
                required: true,
                message: '服务费不能为空',
                trigger: 'blur',
              },
            ]"
          >
            <el-input-number v-model="inputForm.setServiceCharge" controls-position="right" :min="0"></el-input-number>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="24" v-if="method === 'add'">
          <div style="display: flex">
            <el-form-item
              label="参与范围:"
              prop="serviceNo"
              :rules="[
                {
                  required: true,
                  message: '参与范围不能为空',
                  trigger: 'blur',
                },
              ]"
            >
              <select-page
                ref="searchSerSelect"
                label="serviceName"
                value="serviceNo"
                :select.sync="inputForm.serviceNo"
                :url="website.searchLink.serviceUrl"
                placeholder-text="服务商"
                filter-key="searchParam"
                multiple
              ></select-page>
            </el-form-item>
            <el-form-item prop="hasChild" label="">
              <el-checkbox
                v-model="inputForm.hasChild"
                true-label="1"
                false-label="0"
                >包含下级</el-checkbox
              >
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="24" v-if="method === 'edit'">
            <el-form-item
              label="服务商配置:"
              :rules="[]"
            >
              <el-button type="primary" @click="handleService">点击查看或设置</el-button>
            </el-form-item>
        </el-col> -->
        <el-col :span="24">
          <el-form-item
            prop="timeDate"
            label="有效期"
            :rules="[
              {
                required: true,
                message: '有效期不能为空',
                trigger: 'blur',
              },
            ]"
          >
            <el-date-picker
              v-model="inputForm.timeDate"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              @change="timeDateChange"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            label="优先级:"
            prop="sortNo"
            :rules="[
              {
                required: true,
                message: '优先级不能为空',
                trigger: 'blur',
              },
            ]"
          >
            <el-input
              v-model="inputForm.sortNo"
              placeholder="请填写优先级"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            label="套餐logo:"
            prop="logo"
            :rules="[
              {
                required: true,
                message: 'logo不能为空',
                trigger: 'blur',
              },
            ]"
          >
            <el-upload
              action=""
              list-type="picture-card"
              :http-request="httplogoRequest"
              :limit="1"
              :on-remove="logoRemove"
              :before-remove="beforelogoRemove"
              :file-list="logoFileList"
              :before-upload="beforeUpload"
              :on-preview="imgPreview"
              :on-exceed="handHeldExceed"
            >
              <i slot="default" class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-image-viewer
        style="z-index: 99999"
        v-if="imgShow"
        :on-close="
          () => {
            imgShow = false;
          }
        "
        :url-list="imgUrlList"
      ></el-image-viewer>
      <avue-crud
        :option="option"
        :search.sync="search"
        :table-loading="loading"
        :data="inputForm.productList"
        :page.sync="page"
        :permission="permissionList"
        :before-open="beforeOpen"
        v-model="form"
        ref="crud"
        @row-update="rowUpdate"
        @row-save="rowSave"
        @row-del="rowDel"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
        @sort-change="sortChange"
        @on-load="onLoad"
      >
        <template slot="menuLeft">
          <!-- <el-button
          type="danger"
          size="small"
          icon="el-icon-delete"
          plain
          @click="handleDelete"
          >删 除
        </el-button> -->
        </template>
        <template slot="menuRight">
          <span style="margin-right: 5px" v-if="page.allPrice">
            <span style="color: #999">套餐总金额：</span>
            <span class="redFont">{{ page.allPrice }}元</span>
          </span>
        </template>
      </avue-crud>
      <el-row :gutter="15">
        <div style="margin-top: 30px" class="line-bottom">活动考核</div>
        <el-col :span="12">
          <el-form-item
            label="机构活动奖励:"
            prop="orgActiveCode"
          >
            <el-select
              class="width-100"
              size="small"
              v-model="inputForm.orgActiveCode"
              placeholder="请选择机构活动奖励"
              filterable
              clearable
            >
              <el-option
                v-for="item in orgActiveCodeList"
                :key="item.activeCode"
                :label="item.activeName"
                :value="item.activeCode"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="服务商活动奖励:"
            prop="serviceActiveCode"
          >
            <el-select
              class="width-100"
              size="small"
              v-model="inputForm.serviceActiveCode"
              placeholder="请选择服务商活动奖励"
            >
              <el-option
                v-for="item in serviceActiveCodeList"
                :key="item.activeCode"
                :label="item.activeName"
                :value="item.activeCode"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="服务商考核内容:"
            prop="serviceAssessCode"
          >
            <el-select
              class="width-100"
              size="small"
              v-model="inputForm.serviceAssessCode"
              placeholder="请选择服务商考核内容"
            >
              <el-option
                v-for="item in serviceAssessCodeList"
                :key="item.activeCode"
                :label="item.activeName"
                :value="item.activeCode"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="商户活动奖励:"
            prop="merchantActiveCode"
          >
            <el-select
              class="width-100"
              size="small"
              v-model="inputForm.merchantActiveCode"
              placeholder="请选择商户活动奖励"
            >
              <el-option
                v-for="item in merchantActiveCodeList"
                :key="item.activeCode"
                :label="item.activeName"
                :value="item.activeCode"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="15">
        <div style="margin-top: 30px" class="line-bottom">活动详情</div>
        <el-col :span="24">
          <el-form-item label-width="0" prop="content">
            <avue-ueditor
              v-model="inputForm.content"
              :options="ueditorOptions"
            ></avue-ueditor>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-dialog
      class="avue-dialog"
      title="服务商"
      top="2%"
      :width="screenWidth > 1920
          ? '65%'
          : screenWidth <= 1920 && screenWidth > 1500
          ? '65%'
          : '80%'"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="serviceDialog"
      v-if="serviceDialog"
      :before-close="handleCloseService"
    >
      <serviceTables ref="serviceTable" :mealCode="inputForm.mealCode"></serviceTables>
    </el-dialog>
  </div>
</template>

<script>
import { getDictionary } from "@/api/system/dict";
import { getList } from "@/api/rb-oem/activity/activity";
import { uploadPublic } from "@/api/system/oss";
import serviceTables from "../components/servicetables";
export default {
  props: {
    inputForm: {
      type: Object,
      default: () => {
        return {
          id: "",
          beginDate: "",
          content: "",
          endDate: "",
          hasChild: "0",
          ifRefund: 0,
          ifRefundAmt: 0,
          ifReturn: 0,
          ifReturnAmt: 0,
          setServiceCharge: 0,
          isEnable: "1",
          logo: "",
          mealActiveType: "",
          mealCode: "",
          mealName: "",
          mealType: "",
          merchantActiveCode: "",
          orgActiveCode: "",
          productList: [],
          serviceActiveCode: "",
          serviceAssessCode: "",
          serviceNo: "",
          sortNo: "",
          timeDate: [],
        };
      },
    },
    method: {
      type: String,
      default: "",
    },
  },
  components: {
    serviceTables
  },
  data() {
    return {
      screenWidth: document.documentElement.clientWidth,
      imgShow: false,
      imgUrlList: [],
      logoFileList: [],
      loading: false,
      mealTypeList: [],
      mealActiveTypeList: [],
      isEnableList: [],
      orgActiveCodeList: [],
      serviceActiveCodeList: [],
      serviceAssessCodeList: [],
      merchantActiveCodeList: [],
      data: [],
      search: {},
      form: {},
      query: {},
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
        allPrice: 0,
      },
      props: {
        //菜单权限数据 props
        label: "title",
        value: "key",
      },
      option: {
        //height: "auto",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        selection: true,
        searchMenuSpan: 6,
        search: false,
        // columnBtn: false,
        addBtn: true,
        editBtn: true,
        column: [
          {
            label: "主键",
            prop: "id",
            type: "input",
            sortable: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
          },
          {
            label: "商品名称",
            prop: "productName",
            slot: true,
            overHidden: true,
            rules: [
              {
                required: true,
                message: "请输入商品名称",
                trigger: "blur",
              },
            ],
          },
          {
            label: "商品型号",
            prop: "productType",
            overHidden: true,
            rules: [
              {
                required: true,
                message: "请输入商品型号",
                trigger: "blur",
              },
            ],
          },
          {
            label: "是否可退",
            prop: "ifRefund",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=pledge_if_refund",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "string",
            showColumn: false,
            rules: [
              {
                required: true,
                message: "请选择是否可退",
                trigger: "blur",
              },
            ],
            control: (val, form) => {
              return new Promise((resolve) => {
                // console.log(form, 'form');
                if (val === "0") {
                  resolve({
                    ifRefundAmt: {
                      value: "",
                      disabled: false,
                    },
                  });
                } else if (val === "1") {
                  resolve({
                    ifRefundAmt: {
                      value: "0",
                      disabled: true,
                    },
                  });
                }
              });
            },
          },
          {
            label: "是否可返",
            prop: "ifReturn",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=pledge_if_return",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "string",
            showColumn: false,
            rules: [
              {
                required: true,
                message: "请选择是否可返",
                trigger: "blur",
              },
            ],
          },
          {
            label: "押金价格",
            prop: "price",
            overHidden: true,
            hide: true,
            rules: [
              {
                required: true,
                message: "请输入押金价格",
                trigger: "blur",
              },
            ],
          },
          {
            label: "退还金额",
            prop: "ifRefundAmt",
            overHidden: true,
            rules: [
              {
                required: true,
                message: "请输入退还金额",
                trigger: "blur",
              },
            ],
          },
          {
            label: "返现金额",
            prop: "ifReturnAmt",
            overHidden: true,
            rules: [
              {
                required: true,
                message: "请输入返现金额",
                trigger: "blur",
              },
            ],
          },
          {
            label: "商品大图",
            prop: "logo",
            type: "upload",
            listType: "picture-img",
            action: "/api/blade-resource/oss/endpoint/put-file-public",
            loadText: "图片上传中，请稍等",
            limit: 1,
            fileSize: 10240,
            span: 24,
            propsHttp: {
              res: "data",
              url: "link",
            },
            tip: "只能上传jpg/png文件，且不且不超过10Mb",
            showColumn: false,
            rules: [
              {
                required: true,
                message: "请上传商品大图",
                trigger: "blur",
              },
            ],
          },
          {
            label: "允许复购",
            prop: "isRepurchase",
            type: "select",
            dicUrl:
              "/api/blade-system/dict/dictionary?code=pledge_is_repurchase",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "string",
            showColumn: false,
            rules: [
              {
                required: true,
                message: "请选择是否允许复购",
                trigger: "blur",
              },
            ],
          },
        ],
      },
      ueditorOptions: {
        //普通上传地址
        action: "/api/blade-resource/oss/endpoint/put-file",
        customConfig: {}, //wangEditor编辑的配置
        props: {
          // home: '',
          res: "data",
          url: "link",
        },
      },
      serviceDialog: false,
    };
  },
  watch: {
    method: {
      handler(val) {
        if (val === 'view') {
          this.option.editBtn = false
          this.option.delBtn = false
        } else {
          this.option.editBtn = true
          this.option.delBtn = true
        }
      },
      immediate: true,
      // deep: true
    },
    'inputForm': {
      handler(val) {
        if (val) {
          this.doGetDicts();
        }
      },
      immediate: true,
      // deep: true
    }
  },
  created() {
    // this.doGetDicts();
  },
  methods: {
    /* 字典 */
    doGetDicts() {
      getDictionary({ code: "pledge_meal_type" }).then((res) => {
        this.mealTypeList = res.data.data;
      });
      getDictionary({ code: "pledge_meal_active_type" }).then((res) => {
        this.mealActiveTypeList = res.data.data;
      });
      getDictionary({ code: "pledge_is_enable" }).then((res) => {
        this.isEnableList = res.data.data;
      });
      getDictionary({ code: "pledge_check_user_type" }).then((res) => {
        this.checkUserTypeList = res.data.data;
      });
      getList(
        "-1",
        "-1",
        Object.assign(this.query, { userType: 1, activeType: 1 })
      ).then((res) => {
        this.orgActiveCodeList = res.data.data.records;
      });
      getList(
        "-1",
        "-1",
        Object.assign(this.query, { userType: 2, activeType: 1 })
      ).then((res) => {
        this.serviceActiveCodeList = res.data.data.records;
      });
      getList(
        "-1",
        "-1",
        Object.assign(this.query, { userType: 2, activeType: 2 })
      ).then((res) => {
        this.serviceAssessCodeList = res.data.data.records;
      });
      getList(
        "-1",
        "-1",
        Object.assign(this.query, { userType: 3, activeType: 1 })
      ).then((res) => {
        this.merchantActiveCodeList = res.data.data.records;
      });
      this.$nextTick(()=>{
        if (this.inputForm.beginDate && this.inputForm.endDate) {
            this.$set(this.inputForm, 'timeDate', [this.inputForm.beginDate, this.inputForm.endDate])
        }
        this.$forceUpdate()
      })
    },
    handleService() {
      this.serviceDialog = true;
      this.$nextTick(()=>{
        // this.$refs['serviceTable'].refreshList();
      })
    },
    handleCloseService(done){
      this.$refs['serviceTable'].id = '';
      this.serviceDialog = false;
      // this.addForm.serviceList = this.$refs.serviceWhite.allData
      done()
    },
    timeDateChange(e) {
      this.inputForm.beginDate = e[0];
      this.inputForm.endDate = e[1];
    },
    /* 预览图片 */
    imgPreview(file) {
      this.imgUrlList[0] = file.url;
      this.imgShow = true;
    },
    beforeUpload(file) {},
    /* 文件超出个数限制时的钩子 */
    handHeldExceed() {
      this.$message.error("只能上传一张图片哦~");
    },
    /* 上传 */
    httplogoRequest(option) {
      uploadPublic(option.file, option.file.name).then((res) => {
        this.inputForm.logo = res.data.data.link;
        this.$refs.inputForm.validateField("logo");
      });
    },
    /* 删除 */
    logoRemove(file, fileList) {
      this.logoFileList = fileList;
      this.inputForm.logo = "";
    },
    beforelogoRemove() {
      return this.$confirm(`确定移除非法人身份证正面照片？`);
    },
    /**
     * @func 选中单元格
     * @desc 选中单元格数据
     * @param {list} list --- 选中单元格数据-数组
     * */
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    /**
     * @func 分页页码
     * @desc 分页页码改变时会触发
     * */
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      // this.refreshChange();
    },
    /**
     * @func 当前页个数
     * @desc pageSize改变时会触发
     * */
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      // this.refreshChange();
    },
    /**
     * @func 刷新
     * @desc 点击刷新按钮触发该事件
     * */
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    rowSave(row, done, loading) {
      this.inputForm.productList.push(row);
      setTimeout(() => {
        done();
        this.onLoad(this.page);
      }, 300);
    },
    rowUpdate(row, index, done, loading) {
      this.$nextTick(() => {
        this.inputForm.productList[index] = Object.assign(
          this.inputForm.productList[index],
          {
            ...row,
          }
        );
      });
      setTimeout(() => {
        done();
      }, 300);
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return this.inputForm.productList.splice(row.$index, 1);
        })
        .then(() => {
          this.onLoad(this.page);
        });
    },
    onLoad() {
      this.loading = true;
      let total = 0;
      for (const item of this.inputForm.productList) {
        total += Number(item.price);
      }
      this.$nextTick(() => {
        this.page.allPrice = Number(total.toFixed(2));
      });
      //   this.$forceUpdate();
      setTimeout(() => {
        this.loading = false;
      }, 300);
      //   if (this.awaitData.length > 0) {
      //     //awaitData为全部数据，data是目前表格绑定的数据
      //     this.data = this.awaitData.slice(
      //       (this.page.currentPage - 1) * this.page.pageSize,
      //       this.page.currentPage * this.page.pageSize
      //     );
      //     this.page.total = this.awaitData.length;
      //   }
      //   this.loading = false;
    },
  },
};
</script>

<style>
.redFont {
  color: red;
}
</style>